<?php	

	define('ChartType','Horizontal');
	
	if (isset($_POST['Category'])) {
		
		include_once('../../config.php'); 
		session_start();
		LinkDataBase();
		$Array_Field = FieldLocationGet($_POST['Category']);
				
		$Field = implode(", ",$Array_Field);
		
		//Find question.
		$sql = "select ".$_POST['filename'][0].".table_name AS table_name, item, total, ".$Field." 
				FROM ".$_POST['filename'][0]." LEFT JOIN sheet 
				ON ".$_POST['filename'][0].".table_name = binary(sheet.table_name) 
				WHERE table_number='".$_POST['tablename']."' AND 
				item NOT LIKE '%Base: All Respondents%' AND 
				item NOT LIKE '%Base: Respondents%'";
 		
		$result= mysql_query($sql);
		$numResult = mysql_num_rows($result);
		
		if ($numResult > 0) {
		?>
                
			<script type="text/javascript">
			
			var sub_QAname = '';
			var sub_table = '';

			var data = new google.visualization.DataTable();
  			data.addColumn('string', 'Area');
			var myrow = new Array();
			var Array_Temp = new Array();
			<?php
			
			$item = "";
			$index = 0;
			$Previous_Column_ByCheck = '';
			while($row = mysql_fetch_assoc($result)) {
				
				//Find Column name and define array.
				if ($row['total']=='Total') {
					$tablename = $row['table_name'];
					for ($i=0; $i<count($Array_Field); $i++) {
					?>
						var index = <?php echo $i;?>;
						var DB_title = '<?php echo $row[$Array_Field[$i]];?>';
						myrow[index] = new Array();
						myrow[index].push(DB_title);
					<?php
					}
				}
				
				if ((($item!="")&&($row['item']!='Sigma')&&
					(strpos($row['total'],'%'))&&
					($_POST['keyword']==''))||
					//For keyword exists.
					(($item!="")&&($row['item']!='Sigma')&&
					(strpos($row['total'],'%'))&&
					($_POST['keyword']!='')&&
					//contain is YES.
					(((strpos($item,(string)$_POST['keyword']))&&
					($_POST['contain']=='YES'))||
					//contain is NO.
					((!strpos($item,(string)$_POST['keyword']))&&
					($_POST['contain']=='NO'))))) {
						
					$Previous_Column_ByCheck = $row[$Array_Field[0]];
						
					//Check type and Catch next question info for javascript.
					if (isset($_POST['Array_SubXML']['sub_QAname'])) {
						if (is_array($_POST['Array_SubXML']['sub_QAname'])) {
						?>
							sub_QAname = '<?php echo $_POST['Array_SubXML']['sub_QAname'][$index]; ?>\n';
						<?php
							$index++;
						}
						else {
						?>
							sub_QAname = '<?php echo $_POST['Array_SubXML']['sub_QAname']; ?>\n';
						<?php
						}
					}
					
					for ($i=0; $i<count($Array_Field); $i++) {
						
						//Check row is percent or not percent.
						if (strpos($row[$Array_Field[$i]], '%')!==false)
							$value = str_replace('%','',$row[$Array_Field[$i]]) / 100;
						else
							$value = '0.00';
					?>
						var index = <?php echo $i;?>;
						var value = <?php echo $value; ?>;
						
						Array_Temp[index] = new Array();
						
						Array_Temp[index].push(value);
						Array_Temp[index].push(sub_QAname);
						Array_Temp[index].push(Math.round((value*100))+'%');
					<?php
					}
					?>
					data.addColumn('number', '<?php echo str_replace("'","\'",str_replace('(Net)','',$item)); ?>');
					data.addColumn({type: 'string', role: 'tooltip',p: {html:true}});
					<?php
				}
				//Check value to change text color.
				else if ($Previous_Column_ByCheck!='') {
					
					$Previous_Column_ByCheck = '';
					
					for ($i=0; $i<count($Array_Field); $i++) {
						?>
							var index = <?php echo $i;?>;
							myrow[index].push(Array_Temp[index][0]);
							<?php
						if ((isset($row[$Array_Field[$i]]))&&(preg_match('/[A-Z]+/', $row[$Array_Field[$i]]))) {
					?>
							myrow[index].push('<div style="padding:5px 5px 5px 5px;font-size:16px">'+Array_Temp[index][1]+'<font color="red">'+Array_Temp[index][2]+'</font></div>');
					<?php
						}
						else {
						?>
							myrow[index].push('<div style="padding:5px 5px 5px 5px;font-size:16px">'+Array_Temp[index][1]+Array_Temp[index][2]+'</div>');
						<?php
						}
					}
				}
				else if ($row['item']=='Sigma')
					break;
							
				$item = $row['item'];
			}
				
			for ($i=0; $i<count($Array_Field); $i++) {
			?>
				var index = <?php echo $i;?>;
					
				//console.log(myrow[index]);
				data.addRow(myrow[index]);
			<?php
			}
			?>
			
			var options = {
				tooltip: {isHtml: true},
				chartArea :{top:5, height: data.getNumberOfRows()*data.getNumberOfColumns()*8},
				legend: {position: 'none'},
				hAxis: {textPosition:'out', maxValue:1, minValue:0, format:'#%'},
				height: data.getNumberOfRows()*data.getNumberOfColumns()*8
			};
			
			var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
			chart.draw(data, options);
			
			if (sub_QAname!='') {	
				//Handle event.
				google.visualization.events.addListener(chart, 'select', selectHandler);
			}
			
			function selectHandler(e) {
					
				//Check type and Catch next question info for javascript.
				var sub_ChartType = '';
				var KeyWord = '';
				var Contain = '';
				<?php
				if (isset($_POST['Array_SubXML']['sub_table'])) {
					if (is_array($_POST['Array_SubXML']['sub_table'])) {
				?>
						var selection = chart.getSelection();
						var message = selection[0];
						var index = (message.column-1)/2;
						var Temp_Array_Table = <?php echo json_encode($_POST['Array_SubXML']['sub_table']); ?>;
						var Temp_Array_ChartType = <?php echo json_encode($_POST['Array_SubXML']['sub_charttype']); ?>;
						
						var Temp_Array_KeyWord = <?php echo json_encode($_POST['Array_SubXML']['sub_keyword']); ?>;
						var Temp_Array_Contain = <?php echo json_encode($_POST['Array_SubXML']['sub_contain']); ?>;

						sub_table = Temp_Array_Table[index];
						sub_ChartType = Temp_Array_ChartType[index];
						KeyWord = Temp_Array_KeyWord[index];
						Contain = Temp_Array_Contain[index];
				<?php
					}
					else {
				?>
						sub_table = '<?php echo $_POST['Array_SubXML']['sub_table']; ?>';
						sub_ChartType = '<?php echo $_POST['Array_SubXML']['sub_charttype']; ?>';
						KeyWord = '<?php echo $_POST['Array_SubXML']['sub_keyword']; ?>';
						Contain = '<?php echo $_POST['Array_SubXML']['sub_contain']; ?>';
				<?php
					}
				}
				?>
					
				var year = '<?php echo $_POST['year']; ?>';
				var season = '<?php echo $_POST['season']; ?>';
				var Step = <?php echo $_POST['step']; ?>;
					
				//Check previous title is array or string.
				var Previous_Title = new Array();
				<?php
				if (is_array($_POST['previous_title'])) {
				?>
					Previous_Title = <?php echo json_encode($_POST['previous_title']); ?>;
				<?php
				}
				else {
				?>
					Previous_Title.push('<?php echo $_POST['previous_title']; ?>');
				<?php
				}
				?>
				var Temp = new Array('<?php echo '<a href="#" id="'.$_POST['step'].'" class="'.ChartType.'" onclick="GotoTargetLocation(this);" >'.$_POST['tablename'].'</a>'; ?>',
				'<?php echo $_POST['tablename']; ?>','<?php echo ChartType; ?>', '<?php echo $_POST['keyword']; ?>', '<?php echo $_POST['contain']; ?>');
				Previous_Title.push(Temp);
					
				$("#content-detail").load('../chart/detail/index.php',
				{'year':year, 'season':season, 'tablename': sub_table, 'charttype': sub_ChartType, 
				'keyword': KeyWord, 'contain': Contain, 'step': Step+1, 'previous_title': Previous_Title});
			}
			
			//Created Legend.
			var Height_Legend = (data.getNumberOfColumns()-1)/2*20;
			
			//Set basic height.
			if (data.getNumberOfRows()*data.getNumberOfColumns()*8+Height_Legend<340)
				$('#legend_div').height(340-data.getNumberOfRows()*data.getNumberOfColumns()*8-Height_Legend);
				
			var options_legend = {
				chartArea :{width: 0, height:Height_Legend},
				legend: {position: 'right', textStyle: {color: 'blue', fontSize: 12}},
				hAxis: {textPosition:'none'},
				vAxis: {textPosition:'none'},
				height: Height_Legend
			};
			
			var chart_Legend = new google.visualization.BarChart(document.getElementById('legend_div'));
			chart_Legend.draw(data, options_legend);
			
         </script>
<?php
		}
	}
?>
<div id="chart_div" style="width: 770;margin-bottom:30px;" class="right-image"></div><br/>
<div id="legend_div" style="width: 770;margin-bottom:30px;" class="right-image"></div>